﻿package com.bizmlib.utils
{
	import flash.text.TextField;
	import flash.text.TextLineMetrics;
	

	public function truncateTextInField(textField:TextField, suffix:String = "…", lineIndex:int = 0):void
	{
		//traceExternally("truncateTextInField(" + arguments + ")");
		
		var lineText:String = textField.getLineText(lineIndex);
		var lineMetrics:TextLineMetrics = textField.getLineMetrics(lineIndex);
		var textWidthMargin:Number = 30;
		
		while(lineMetrics.width > textField.width - textWidthMargin)
		{
			//traceExternally(lineMetrics.width + "\t" + textField.width + "\t" + lineText);
			
			lineText = lineText.substring(0, lineText.length - 2);
			updateTextFieldLine(textField, lineText, lineIndex);
			lineMetrics = textField.getLineMetrics(lineIndex);
		}
		
		var reg:RegExp = /(.*)(\n|\r)(.*)/gm;
		var res:Object = reg.exec(lineText);
		if(res)
			lineText = res[1] + suffix + res[2] + res[3];
		else
			lineText += suffix;
		updateTextFieldLine(textField, lineText, lineIndex);
	}
}